package com.libinyn.base.pms.serivce.impl.sys;


import com.libinyn.base.pms.common.utils.Constant;
import com.libinyn.base.pms.entity.sys.SysMenuEntity;
import com.libinyn.base.pms.entity.sys.SysUserEntity;
import com.libinyn.base.pms.entity.sys.SysUserTokenEntity;
import com.libinyn.base.pms.mapper.sys.SysMenuMapper;
import com.libinyn.base.pms.mapper.sys.SysUserMapper;
import com.libinyn.base.pms.mapper.sys.SysUserTokenMapper;
import com.libinyn.base.pms.serivce.sys.ShiroService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class ShiroServiceImpl implements ShiroService {

    @Resource
    private SysMenuMapper sysMenuMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysUserTokenMapper sysUserTokenMapper;

    @Override
    public Set<String> getUserPermissions(long userId) {
        List<String> permsList;

        //系统管理员，拥有最高权限
        if(userId == Constant.SUPER_ADMIN){
            List<SysMenuEntity> menuList = sysMenuMapper.selectAll();
            permsList = new ArrayList<>(menuList.size());
            for(SysMenuEntity menu : menuList){
                permsList.add(menu.getPerms());
            }
        }else{
            permsList = sysUserMapper.queryAllPerms(userId);
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String perms : permsList){
            if(StringUtils.isBlank(perms)){
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }

    @Override
    public SysUserTokenEntity queryByToken(String token) {
        SysUserTokenEntity tokenEntity = new SysUserTokenEntity();
        tokenEntity.setToken(token);
        return sysUserTokenMapper.selectOne(tokenEntity);
    }

    @Override
    public SysUserEntity queryUser(Long userId) {
        return sysUserMapper.selectByPrimaryKey(userId);
    }
}
